//@target illustrator

String.prototype.clearSpace = function(){
  return this.replace(/(^\s*)|(\s*$)/g, "")
}
String.prototype.toAiColor = function(){
  // 支持字符格式为: '100 70 30 0, 128 256 0' 或者 '128 0 0' (rgb 可使用 HEX)
  var colors = this.clearSpace().split(',')
  color = colors[0].hex2rgb().split(' ')
  var isRGBSpace = app.activeDocument.documentColorSpace === DocumentColorSpace.RGB
  if (colors.length === 2 && isRGBSpace) {
    color = colors[1].clearSpace().hex2rgb().split(' ')
  }
  try {
    if(color.length === 3) {
      var newColor = new RGBColor();
      newColor.red = color[0];
      newColor.green = color[1];
      newColor.blue = color[2];
    } else if(color.length === 4) {
      var newColor = new CMYKColor();
      newColor.cyan = color[0];
      newColor.magenta = color[1];
      newColor.yellow = color[2];
      newColor.black = color[3];
    }
    return newColor
  } catch (e) {
    var newColor = new RGBColor();
    newColor.red = 0;
    newColor.green = 0;
    newColor.blue = 0;
  }
  return newColor
}

String.prototype.hex2rgb = function(){
  // '#888' => '128 128 128'
  var sColor = this.toLowerCase();
  //十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (var i=1; i<4; i+=1) {
        sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));
      }
      sColor = sColorNew;
    }
    //处理六位的颜色值
    var sColorChange = [];
    for (var i=1; i<7; i+=2) {
      sColorChange.push(parseInt("0x"+sColor.slice(i, i+2)));
    }
    return sColorChange.join(" ");
  }
  return sColor;
};


var svgCode = '<svg version="1.1" id="jetta-logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 76" style="enable-background:new 0 0 100 76;" xml:space="preserve"> <path d="M28,71h9v5H22V52h14v5h-8v4.5h7v5h-7V71z M41,57h5v19h6V57h5v-5H41V57z M3.56,57H10v11c0,1.66-1.34,3-3,3H0.9 L0,76h9c3.87,0,7-3.13,7-7V52H4.43L3.56,57z M62,57h5v19h6V57h5v-5H62V57z M92.24,67L90,56.51L87.76,67H92.24z M93.22,72h-6.44 L86,76h-6l6-24h8l6,24h-6L93.22,72z M98.55,7.02C101.57,3.56,99.44,0,96.09,0H3.31C0.47,0-1.04,3.34,0.82,5.47L4.78,10h63.73 c0.95,0,1.45,1.11,0.83,1.82L55.83,27.27C54.31,29,52.11,30,49.81,30H23.39c-0.43,0-0.66,0.51-0.38,0.83l3.54,4.05 C29.4,38.13,33.51,40,37.84,40h25.04c4.33,0,8.44-1.87,11.29-5.12L98.55,7.02"/> </svg>'
var svgGroup = insertSvg(svgCode)
svgGroup.pageItems[0].pathItems[0].fillColor = '90 55 0 0, #285aff'.toAiColor()

function insertSvg(code, color) {
    var svgFileName = "inlineSVGtoAI.svg";
    var svgFile = new File("" + Folder.temp + "/" + svgFileName);
    svgFile.open("w");
    
    svgFile.write(code);
    svgFile.close();

    var doc = app.activeDocument;
    var placed = doc.groupItems.createFromFile(svgFile);

    $.sleep(500);
    svgFile.remove();

    return placed
}


if (app.documents.length > 0 && app.activeDocument.pathItems.length > 0) {
  var CURR_DOC = app.activeDocument;
  var CURR_ARTBOARD_INDEX = CURR_DOC.artboards.getActiveArtboardIndex()
  var CURR_ARTBOARD = CURR_DOC.artboards[CURR_ARTBOARD_INDEX].artboardRect

  setLogoGroup()
}

/* ============================================================ */
function setLogoGroup() {
  var artboardSize = _getArtboardSize(CURR_ARTBOARD)
  var artboardShortSide = artboardSize.width < artboardSize.height ? artboardSize.width : artboardSize.height
  var logoGroupScaleRatio = getLogoRatio(artboardSize)
  var LOGO_RATIO = 0.526314
  var logoGroupHeight = artboardShortSide * logoGroupScaleRatio
  var distance = logoGroupHeight * LOGO_RATIO
  _setSizeAndPosition({x: artboardSize.x + distance, y: artboardSize.y - distance}, logoGroupHeight)
}

function getLogoRatio(rectangle) {
    var ratioRange =  [1,    4/3,  7/5,  3/2,  16/9, 2,   3,   5,   9,   10];
    var logoRatios = [[0.4,  0.4,  0.4,  0.4,  0.4,  0.4, 0.4, 0.4, 0.4, 0.4],
                      [0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.3, 0.3, 0.4],
                      [0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.3, 0.3, 0.4]]
    var W = rectangle.width || 1;
    var H = rectangle.height || 1;
    var rectRatio = W > H ? W / H : H / W;
    var ratioIndex = _getArrIndex_(ratioRange, rectRatio) - 1
    var typesRange = [130, 560]
    var shortSide = W < H ? W : H;
    var typeIndex = _getArrIndex_(typesRange, shortSide)
    return logoRatios[typeIndex][ratioIndex]
}

/* ================== Public Base Function ========================================== */

// functions
// setSizeAndPosition({x: -100, y: 200}, 100)
/* todo 默认以px为单位，需要增加单位判断 */
function _setSizeAndPosition (position, height) {
  var doc = app.activeDocument;
  if (doc.selection.length < 1) {
    alert(':-) 请选好图形后，再试试')
    return
  }
  var curr = doc.selection[0]
  var ratio = curr.width / curr.height || 1

  if  (position) {
    curr.left = position.x
    curr.top = position.y
  }
  if (height) {
    curr.height = height
    curr.width = height * ratio
  }
}

function _getArtboardSize(canvas) {
    var rect = canvas.toString().split(',')
    var x1 = +rect[0]
    var y1 = +rect[1]
    var x2 = +rect[2]
    var y2 = +rect[3]
    var rectangle = {
        y: y1,
        x: x1,
        width: Math.abs(x2 - x1),
        height: Math.abs(y2 - y1)
    }
    return rectangle
}

/* ================== Js untis Functions ========================================== */

function _getArrIndex_(arr, num) {
  var index = 0;
  var len = arr.length
  if (num >= arr[len - 1]) {
    return len
  }
	while(arr[index] <= num) {
		index += 1;
	}
	return index;
}